package data

import (
	"context"
	"fmt"
	"service/model/mod"
	"strconv"
	"strings"
	"time"

	model "service/model/crm_base"
	mCache "service/model/hr_cache"

	gpc "gitee.com/cloudapex/protos/comm/pb"
	gpb "gitee.com/cloudapex/protos/crm_base/pb"
	gpa "gitee.com/cloudapex/protos/hr_cache/pb"

	"service/api/crm/order"

	"gitee.com/cloudapex/ulern/htp"
	"gitee.com/cloudapex/ulern/util"
	"github.com/gin-gonic/gin"
)

// 数据列表公共入参表
type CommDataInParam struct {
	CsId   int64 `form:"csId" json:"csId" binding:"omitempty"`     // 客户Id
	UserId int64 `form:"userId" json:"userId" binding:"omitempty"` // 坐席Id
	Phone  int64 `form:"phone" json:"phone" binding:"omitempty"`   // 手机号
	ProjId int64 `form:"projId" json:"projId" binding:"omitempty"` // 项目Id
}

/*
 * 描述: 库存列表[未分配]
 * 路由: /data/baseList
 * 方法: GET
 *********************************************************************/
type BaseList struct {
	mod.SortFinder // 1:入库时间 2:回库时间
	mod.PageFinder

	CommDataInParam // 公共入参

	InBgn   int64  `form:"inBgn" json:"inBgn" binding:"omitempty"`     // 入库时间(int)
	InEnd   int64  `form:"inEnd" json:"inEnd" binding:"omitempty"`     // 入库时间(int)
	BackBgn int64  `form:"backBgn" json:"backBgn" binding:"omitempty"` // 回库时间(int)
	BackEnd int64  `form:"backEnd" json:"backEnd" binding:"omitempty"` // 回库时间(int)
	ShowId  uint64 `form:"showId" json:"showId" binding:"omitempty"`   //组织架构id

	// 时间条件
	cTimes []*gpc.TimeReq
}
type baseRspItem struct {
	Base model.BaseBase    `json:"baseBase"`
	Proj model.BaseProject `json:"baseProject"`
	Tg   model.BaseProTg   `json:"baseProTg"`
}

func (this *BaseList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	var showids []uint64
	if !mod.IsArmy(user.ShowId) {
		showids = mod.SectionDecovered(user.ShowId)
		if this.ShowId != 0 {
			bl := order.IsGetFrame(showids, this.ShowId)
			if !bl {
				return htp.RespOK("", &struct {
					Total int64       `json:"total"`
					List  interface{} `json:"list"`
				}{0, []*firstRspItem{}})
			}
			showids = []uint64{this.ShowId}
		}
	} else {
		showids = append(showids, this.ShowId)
	}

	util.Debug("组织架构%s", showids)

	// 时间条件
	if resp := this.HandleCondiTimes(c, ctx); resp.Err() != nil {
		return resp
	}

	rsp, err := model.Base.GetPoolList(ctx, &gpb.BasePoolReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1),
		Type:    1, // 未分配
		ShowIds: showids,
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{
				Phone: this.Phone,
			},
			BaseProject: &gpb.BaseProject{
				Id:      uint64(this.CsId),
				UId:     this.UserId,
				CId:     user.CId,
				PId:     this.ProjId,
				Logic:   int64(model.EBaseL_Open),
				TimeReq: this.cTimes,
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	util.Debug("cessss%s")

	util.Debug("%s", &gpb.BasePoolReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1),
		Type:    1, // 未分配
		ShowIds: showids,
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{
				Phone: this.Phone,
			},
			BaseProject: &gpb.BaseProject{
				Id:      uint64(this.CsId),
				UId:     this.UserId,
				CId:     user.CId,
				PId:     this.ProjId,
				Logic:   int64(model.EBaseL_Open),
				TimeReq: this.cTimes,
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})

	items := []*baseRspItem{}
	if err := util.Convert(&items, rsp.BasePool); err != nil {
		return htp.RespConvertErr("", err)
	}

	if resp := this.HandleProjNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleFrameNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleUserNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{rsp.Count, items})
}
func (this *BaseList) HandleCondiTimes(c *gin.Context, ctx context.Context) htp.Response {
	if this.InBgn != 0 { // 入库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 1, Start: this.InBgn, End: this.InEnd})
	}
	if this.BackBgn != 0 { // 回库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 2, Start: this.BackBgn, End: this.BackEnd})
	}
	return htp.RespOK("", nil)
}
func (this *BaseList) HandleProjNames(c *gin.Context, ctx context.Context, items []*baseRspItem) htp.Response {
	user := mod.CurrUser(c)

	names, err := model.Proj.GetProjIdNames(ctx, user.CId)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		it.Proj.ProjName = names[it.Proj.PId]
	}
	return htp.RespOK("", nil)
}
func (this *BaseList) HandleFrameNames(c *gin.Context, ctx context.Context, items []*baseRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Proj.StationShow)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Proj.ShowName = mapShowNames[it.Proj.StationShow]
	}
	return htp.RespOK("", nil)
}
func (this *BaseList) HandleUserNames(c *gin.Context, ctx context.Context, items []*baseRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Proj.UId, it.Proj.FirstId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Proj.UName = mapNames[it.Proj.UId]
		it.Proj.FirstName = mapNames[it.Proj.FirstId]
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 首咨列表[未分配]
 * 路由: /data/firstList
 * 方法: GET
 *********************************************************************/
type FirstList struct {
	mod.SortFinder // 1:入库时间
	mod.PageFinder

	CommDataInParam // 公共入参

	TGChannel int `form:"tgChannel" json:"tgChannel" binding:"omitempty"` // 推广渠道
	TGMode    int `form:"tgMode" json:"tgAssign" binding:"omitempty"`     // 推广方式

	InBgn  int64  `form:"inBgn" json:"inBgn" binding:"omitempty"`   // 入库时间(int)
	InEnd  int64  `form:"inEnd" json:"inEnd" binding:"omitempty"`   // 入库时间(int)
	Type   int64  `form:"type" json:"type" binding:"required"`      //  1:首咨  2： 效率
	Days   int64  `form:"days" json:"days" binding:"omitempty"`     //回公海天数
	ShowId uint64 `form:"showId" json:"showId" binding:"omitempty"` //组织架构id
}
type firstRspItem struct {
	Base model.BaseBase    `json:"baseBase"`
	Proj model.BaseProject `json:"baseProject"`
	Tg   model.BaseProTg   `json:"baseProTg"`
}

func (this *FirstList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	var showids []uint64
	if this.Type == 1 {
		if !mod.IsArmy(user.ShowId) {
			showids = mod.SectionDecovered(user.ShowId)
			if this.ShowId != 0 {
				bl := order.IsGetFrame(showids, this.ShowId)
				if !bl {
					return htp.RespOK("", &struct {
						Total int64       `json:"total"`
						List  interface{} `json:"list"`
					}{0, []*firstRspItem{}})
				}
				showids = []uint64{this.ShowId}
			}
		} else {
			if this.ShowId != 0 {
				showids = append(showids, this.ShowId)
			}
		}
		util.Debug("组织架构%s", showids)
	} else {

		if this.ShowId != 0 {
			showids = append(showids, this.ShowId)
		}
	}

	// 时间条件
	cTimes := []*gpc.TimeReq{}
	if this.InBgn != 0 {
		cTimes = append(cTimes, &gpc.TimeReq{Tag: 1, Start: this.InBgn, End: this.InEnd})
	}

	if this.Days != 0 {
		cTimes = append(cTimes, &gpc.TimeReq{Tag: 9, Start: time.Now().Unix() + (this.Days-1)*86400, End: time.Now().Unix() + (this.Days)*86400})
	}
	basePoolRes := &gpb.BasePoolReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1),
		//Type:    1, // 未分配
		ShowIds: showids,
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{
				Phone: this.Phone,
			},
			BaseProject: &gpb.BaseProject{
				Id:  uint64(this.CsId),
				UId: this.UserId,
				CId: user.CId,
				PId: this.ProjId,
				//Logic:   int64(model.EBaseL_First),
				TimeReq: cTimes,
			},
			BaseProTg: &gpb.BaseProTg{
				ChannelId: int64(this.TGChannel),
				WayId:     int64(this.TGMode),
			},
		},
	}

	if this.Type == 1 {
		basePoolRes.Type = 1
		basePoolRes.BasePool.BaseProject.Logic = int64(model.EBaseL_First)
	} else if this.Type == 2 {
		basePoolRes.BasePool.BaseProject.Logic = int64(model.EBaseL_Efficient)
	}

	rsp, err := model.Base.GetPoolList(ctx, basePoolRes)
	if err != nil {
		return htp.RespModelErr("", err)
	}

	items := []*firstRspItem{}
	if err := util.Convert(&items, rsp.BasePool); err != nil {
		return htp.RespConvertErr("", err)
	}

	if resp := this.HandleProjNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleFrameNamesNew(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleUserNames(c, ctx, items); resp.Err() != nil {
		return resp
	}
	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{rsp.Count, items})
}
func (this *FirstList) HandleProjNames(c *gin.Context, ctx context.Context, items []*firstRspItem) htp.Response {
	user := mod.CurrUser(c)

	names, err := model.Proj.GetProjIdNames(ctx, user.CId)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		it.Proj.ProjName = names[it.Proj.PId]
	}
	return htp.RespOK("", nil)
}
func (this *FirstList) HandleFrameNames(c *gin.Context, ctx context.Context, items []*firstRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Proj.ShowId)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Proj.ShowName = mapShowNames[it.Proj.ShowId]
	}
	return htp.RespOK("", nil)
}

func (this *FirstList) HandleFrameNamesNew(c *gin.Context, ctx context.Context, items []*firstRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Proj.StationShow)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Proj.ShowName = mapShowNames[it.Proj.StationShow]
	}
	return htp.RespOK("", nil)
}

func (this *FirstList) HandleUserNames(c *gin.Context, ctx context.Context, items []*firstRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Proj.UId, it.Proj.FirstId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Proj.UName = mapNames[it.Proj.UId]
		it.Proj.FirstName = mapNames[it.Proj.FirstId]
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 首咨|库存列表[已分配时]
 * 路由: /data/firstBaseListed
 * 方法: GET
 *********************************************************************/
type FirstBaseListed struct {
	mod.SortFinder // 3:领取时间 4:沟通时间
	mod.PageFinder

	CommDataInParam // 公共入参

	Logic int64 `form:"logic" json:"Logic" binding:"omitempty"` // 1:首咨(默认) 2:库存

	Logics string `form:"logics" json:"Logics" binding:"omitempty"`

	TGChannel int `form:"tgChannel" json:"tgChannel" binding:"omitempty"` // 推广渠道
	TGMode    int `form:"tgMode" json:"tgAssign" binding:"omitempty"`     // 推广方式

	RecvBgn int64  `form:"recvBgn" json:"recvBgn" binding:"omitempty"` // 领取时间(int)
	RecvEnd int64  `form:"recvEnd" json:"recvEnd" binding:"omitempty"` // 领取时间(int)
	ShowId  uint64 `form:"showId" json:"showId" binding:"omitempty"`   //组织架构id
}
type firstBaseListedRspItem struct {
	Work *model.WorkPool  `json:"workPool"`
	Tg   *model.WorkProTg `json:"workProTg"`
}

func (this *FirstBaseListed) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	fmt.Println(this.Logics)

	var showids []uint64
	if !mod.IsArmy(user.ShowId) {
		showids = mod.SectionDecovered(user.ShowId)
		if this.ShowId != 0 {
			bl := order.IsGetFrame(showids, this.ShowId)
			if !bl {
				return htp.RespOK("", &struct {
					Total int64       `json:"total"`
					List  interface{} `json:"list"`
				}{0, []*firstRspItem{}})
			}
			showids = []uint64{this.ShowId}
		}
	} else {
		showids = append(showids, this.ShowId)
	}

	util.Debug("组织架构%s", showids)

	var list []int64
	if this.Logics != "" {
		logicList := strings.Split(this.Logics, ",")
		for _, v := range logicList {
			v1, _ := strconv.ParseInt(v, 10, 64)
			list = append(list, v1)
		}
	}

	// 时间条件
	cTimes := []*gpc.TimeReq{}
	if this.RecvBgn != 0 { // 领取
		cTimes = append(cTimes, &gpc.TimeReq{Tag: 3, Start: this.RecvBgn, End: this.RecvEnd})
	}
	//logic := int64(model.EBaseL_First)
	//util.Cast(logic == 2, func() { logic = int64(model.EBaseL_Open) }, nil)
	rsp, err := model.Work.GetWorkPoolTgList(ctx, &gpb.WorkPoolTgReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1),
		Type:    2, // 已分配
		ShowIds: showids,
		WorkPoolTg: &gpb.WorkPoolTg{
			WorkPool: &gpb.WorkPool{
				Phone:   this.Phone,
				Id:      uint64(this.CsId),
				UId:     this.UserId,
				CId:     user.CId,
				PId:     this.ProjId,
				Logic:   this.Logic,
				Logics:  list,
				TimeReq: cTimes,
			},
			WorkProTg: &gpb.WorkProTg{
				ChannelId: int64(this.TGChannel),
				WayId:     int64(this.TGMode),
			},
		},
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	items := []*firstBaseListedRspItem{}
	if err := util.Convert(&items, rsp.WorkPoolTg); err != nil {
		return htp.RespConvertErr("", err)
	}

	if resp := this.HandleProjNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleFrameNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleUserNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{rsp.Count, items})
}
func (this *FirstBaseListed) HandleProjNames(c *gin.Context, ctx context.Context, items []*firstBaseListedRspItem) htp.Response {
	user := mod.CurrUser(c)

	names, err := model.Proj.GetProjIdNames(ctx, user.CId)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		it.Work.PName = names[it.Work.PId]
	}
	return htp.RespOK("", nil)
}
func (this *FirstBaseListed) HandleFrameNames(c *gin.Context, ctx context.Context, items []*firstBaseListedRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Work.ShowId)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Work.ShowName = mapShowNames[it.Work.ShowId]
	}
	return htp.RespOK("", nil)
}
func (this *FirstBaseListed) HandleUserNames(c *gin.Context, ctx context.Context, items []*firstBaseListedRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Work.UId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Work.UName = mapNames[it.Work.UId]
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 静默库列表(用户出格审核)
 * 路由: /data/silentList
 * 方法: GET
 *********************************************************************/
type SilentList struct {
	mod.SortFinder // 1:入库时间 5:登记时间
	mod.PageFinder

	CommDataInParam // 公共入参

	InBgn  int64 `form:"inBgn" json:"inBgn" binding:"omitempty"`   // 入库时间(int)
	InEnd  int64 `form:"inEnd" json:"inEnd" binding:"omitempty"`   // 入库时间(int)
	RegBgn int64 `form:"regBgn" json:"regBgn" binding:"omitempty"` // 登记时间(int)
	RegEnd int64 `form:"regEnd" json:"regEnd" binding:"omitempty"` // 登记时间(int)

	// 时间条件
	cTimes []*gpc.TimeReq
}
type silentRspItem struct {
	Base model.BaseBase    `json:"baseBase"`
	Proj model.BaseProject `json:"baseProject"`
	Tg   model.BaseProTg   `json:"baseProTg"`
}

func (this *SilentList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	// 时间条件
	if resp := this.HandleCondiTimes(c, ctx); resp.Err() != nil {
		return resp
	}

	rsp, err := model.Base.GetPoolList(ctx, &gpb.BasePoolReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1),
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{
				Phone: this.Phone,
			},
			BaseProject: &gpb.BaseProject{
				Id:      uint64(this.CsId),
				UId:     this.UserId,
				CId:     user.CId,
				PId:     this.ProjId,
				Logic:   int64(model.EBaseL_Silent),
				TimeReq: this.cTimes,
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	items := []*silentRspItem{}
	if err := util.Convert(&items, rsp.BasePool); err != nil {
		return htp.RespConvertErr("", err)
	}

	if resp := this.HandleProjNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleFrameNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleUserNames(c, ctx, items); resp.Err() != nil {
		return resp
	}
	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{rsp.Count, items})
}
func (this *SilentList) HandleCondiTimes(c *gin.Context, ctx context.Context) htp.Response {
	if this.InBgn != 0 { // 入库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 1, Start: this.InBgn, End: this.InEnd})
	}
	if this.RegBgn != 0 { // 领取
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 3, Start: this.InBgn, End: this.InEnd})
	}
	return htp.RespOK("", nil)
}
func (this *SilentList) HandleProjNames(c *gin.Context, ctx context.Context, items []*silentRspItem) htp.Response {
	user := mod.CurrUser(c)

	names, err := model.Proj.GetProjIdNames(ctx, user.CId)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		it.Proj.ProjName = names[it.Proj.PId]
	}
	return htp.RespOK("", nil)
}
func (this *SilentList) HandleFrameNames(c *gin.Context, ctx context.Context, items []*silentRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Proj.ShowId)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Proj.ShowName = mapShowNames[it.Proj.ShowId]
	}
	return htp.RespOK("", nil)
}
func (this *SilentList) HandleUserNames(c *gin.Context, ctx context.Context, items []*silentRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Proj.UId, it.Proj.FirstId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Proj.UName = mapNames[it.Proj.UId]
		it.Proj.FirstName = mapNames[it.Proj.FirstId]
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 垃圾库列表
 * 路由: /data/junkList
 * 方法: GET
 *********************************************************************/
type JunkList struct {
	mod.SortFinder // 1:入库时间 5:登记时间
	mod.PageFinder

	CommDataInParam // 公共入参

	InBgn  int64 `form:"inBgn" json:"inBgn" binding:"omitempty"`   // 入库时间(int)
	InEnd  int64 `form:"inEnd" json:"inEnd" binding:"omitempty"`   // 入库时间(int)
	RegBgn int64 `form:"regBgn" json:"regBgn" binding:"omitempty"` // 登记时间(int)
	RegEnd int64 `form:"regEnd" json:"regEnd" binding:"omitempty"` // 登记时间(int)

	// 时间条件
	cTimes []*gpc.TimeReq
}
type junkRspItem struct {
	Base model.BaseBase    `json:"baseBase"`
	Proj model.BaseProject `json:"baseProject"`
	Tg   model.BaseProTg   `json:"baseProTg"`
}

func (this *JunkList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	// 时间条件
	if resp := this.HandleCondiTimes(c, ctx); resp.Err() != nil {
		return resp
	}

	rsp, err := model.Base.GetPoolList(ctx, &gpb.BasePoolReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1),
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{
				Phone: this.Phone,
			},
			BaseProject: &gpb.BaseProject{
				Id:      uint64(this.CsId),
				UId:     this.UserId,
				CId:     user.CId,
				PId:     this.ProjId,
				Logic:   int64(model.EBaseL_Junk),
				TimeReq: this.cTimes,
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	items := []*junkRspItem{}
	if err := util.Convert(&items, rsp.BasePool); err != nil {
		return htp.RespConvertErr("", err)
	}

	if resp := this.HandleProjNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleFrameNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleUserNames(c, ctx, items); resp.Err() != nil {
		return resp
	}
	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{rsp.Count, items})
}
func (this *JunkList) HandleCondiTimes(c *gin.Context, ctx context.Context) htp.Response {
	if this.InBgn != 0 { // 入库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 1, Start: this.InBgn, End: this.InEnd})
	}
	if this.RegBgn != 0 { // 领取
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 4, Start: this.InBgn, End: this.InEnd})
	}
	return htp.RespOK("", nil)
}
func (this *JunkList) HandleProjNames(c *gin.Context, ctx context.Context, items []*junkRspItem) htp.Response {
	user := mod.CurrUser(c)

	names, err := model.Proj.GetProjIdNames(ctx, user.CId)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		it.Proj.ProjName = names[it.Proj.PId]
	}
	return htp.RespOK("", nil)
}
func (this *JunkList) HandleFrameNames(c *gin.Context, ctx context.Context, items []*junkRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Proj.ShowId)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Proj.ShowName = mapShowNames[it.Proj.ShowId]
	}
	return htp.RespOK("", nil)
}
func (this *JunkList) HandleUserNames(c *gin.Context, ctx context.Context, items []*junkRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Proj.UId, it.Proj.FirstId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Proj.UName = mapNames[it.Proj.UId]
		it.Proj.FirstName = mapNames[it.Proj.FirstId]
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 库存分配
 * 路由: /data/assign
 * 方法: POST
 *********************************************************************/
const (
	EAssign_PartErr = 1 // 存在部分错误
)

type Assign struct {
	UserId   int64    `form:"userId" json:"userId" binding:"required"`     // 分配给谁
	UserName string   `form:"userName" json:"userName" binding:"required"` // 分配给谁
	CsIds    []uint64 `form:"acct" json:"acct" binding:"required"`         // 客户Ids
	Mode     int32    `form:"mode" json:"mode" binding:"required"`         // 1:未分配机会 2:已分配的机会
}

type PoolRes struct {
	Base model.BaseBase    `json:"baseBase"`
	Proj model.BaseProject `json:"baseProject"`
	Tg   model.BaseProTg   `json:"baseProTg"`
}

func (this *Assign) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	showids, err := order.GetShowIds(ctx, this.UserId)

	if err != nil {
		util.Debug("%s", err)
		return htp.RespModelErr("", err)
	}

	util.Debug("用户的可见范围%s", showids)

	type faildItem struct {
		CustomerId uint64 `json:"customerId"` // 客户ID
		ErrorInfo  string `json:"errInfo"`    // 错误原因
	}
	failds := []faildItem{}

	for _, id := range this.CsIds {
		if this.Mode == 1 { // 处理未分配的机会

			var bres PoolRes

			rsp1, err := model.Base.SelectPool(ctx, &gpb.BasePoolReq{
				BasePool: &gpb.BasePool{
					BaseBase: &gpb.BaseBase{},
					BaseProject: &gpb.BaseProject{
						Id: id,
					},
					BaseProTg: &gpb.BaseProTg{},
				},
			})
			if err != nil {
				failds = append(failds, faildItem{id, fmt.Sprintf("领取机会失败:%s", err.Error())})
				continue
			}

			if err := util.Convert(&bres, rsp1.BasePool); err != nil {
				return htp.RespConvertErr("", err)
			}

			util.Debug("分配的数据详情%s", rsp1)

			if bres.Proj.StationShow == 0 {
				util.Debug("数据没有可见区间%s")
				failds = append(failds, faildItem{id, fmt.Sprintf("分配机会失败:%s", nil)})
				continue
			}

			//数据是否再 用户的可见区间， 用户是否
			bl := order.IsGet(showids, bres.Proj.StationShow)
			if !bl {
				util.Debug("可见范围判断失败%s", bl)
				failds = append(failds, faildItem{id, fmt.Sprintf("分配机会失败:%s", nil)})
				continue
			}

			// 领取机会
			rsp, err := model.Base.GetPool(ctx, &gpb.PoolReq{Id: uint64(id), UId: this.UserId, ShowId: mod.Min(showids)})
			if err != nil {
				failds = append(failds, faildItem{id, fmt.Sprintf("分配机会失败:%s", err.Error())})
				continue
			}
			// 添加工作池
			_, err = model.Work.WorkPoolAdd(ctx, &gpb.WorkPool{
				Id:     rsp.BasePool.BaseProject.Id,
				CId:    user.CId,
				BId:    rsp.BasePool.BaseBase.Id,
				PId:    rsp.BasePool.BaseProject.PId,
				UId:    this.UserId,
				UName:  this.UserName,
				Phone:  rsp.BasePool.BaseBase.Phone,
				ShowId: mod.SectionMaxLv(user.ShowId),
				Levels: rsp.BasePool.BaseProject.Levels,
				Info:   rsp.BasePool.BaseProject.Info,
				Logic:  rsp.BasePool.BaseProject.Logic,
				At:     time.Now().Unix(),
			})
			if err != nil {
				failds = append(failds, faildItem{id, fmt.Sprintf("添加工作池失败:%s", err.Error())})
				continue
			}
		} else { // 处理二次分配

			rsp1, err := model.Base.SelectPool(ctx, &gpb.BasePoolReq{
				BasePool: &gpb.BasePool{
					BaseBase: &gpb.BaseBase{},
					BaseProject: &gpb.BaseProject{
						Id: id,
					},
					BaseProTg: &gpb.BaseProTg{},
				},
			})
			if err != nil {
				failds = append(failds, faildItem{id, fmt.Sprintf("领取机会失败:%s", err.Error())})
				continue
			}

			util.Debug("分配的数据详情%s", rsp1)

			//数据是否再 用户的可见区间， 用户是否
			bl := order.IsGet(showids, rsp1.BasePool.BaseProject.StationShow)
			if !bl {
				util.Debug("可见范围判断失败%s", bl)
				failds = append(failds, faildItem{id, fmt.Sprintf("分配机会失败:%s", err.Error())})
				continue
			}

			_, err = model.Base.EditPool(ctx, &gpb.BasePoolReq{
				BasePool: &gpb.BasePool{
					BaseBase: &gpb.BaseBase{},
					BaseProject: &gpb.BaseProject{
						Id:      id,
						ShareAt: time.Now().Unix(),
						UId:     this.UserId,
						ShowId:  mod.Min(showids),
					},
					BaseProTg: &gpb.BaseProTg{},
				},
			})

			if err != nil {
				failds = append(failds, faildItem{id, fmt.Sprintf("分配机会失败:%s", err.Error())})
				continue
			}

			_, err = model.Work.EditWorkPool(ctx, &gpb.WorkPool{
				Id:    uint64(id),
				UId:   this.UserId,
				UName: this.UserName,
			})
			if err != nil {
				failds = append(failds, faildItem{id, fmt.Sprintf("分配库存失败:%s", err.Error())})
				continue
			}
		}
	}

	if len(failds) > 0 {
		return htp.RespErrData(EAssign_PartErr, "部分操作失败", nil, &struct {
			List interface{} `json:"list"`
		}{failds})
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 出格审核
 * 路由: /data/wayOut
 * 方法: POST
 *********************************************************************/
type WayOut struct {
	Id   int64 `form:"id" json:"id"`                                    //    出格ID
	CsId int64 `form:"csId" json:"csId" binding:"required"`             // 客户Id
	Pass int64 `form:"pass" json:"pass" binding:"required,min=1,max=2"` // 1:驳回 2:通过
}

func (this *WayOut) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)
	if this.Pass == 1 { // 驳回回大库
		_, err := model.Base.SetPoolLogic(ctx, &gpb.PoolLogicReq{Id: uint64(this.CsId), Logic: int64(model.EBaseL_Open)})

		util.Debug("大库的状态：%s:", model.EBaseL_Open)

		if err != nil {
			return htp.RespModelErr("", err)
		}
	} else { // 通过进垃圾库

		fmt.Println(model.EBaseL_Junk)

		util.Debug("垃圾库的代码%s:", model.EBaseL_Junk)

		_, err := model.Base.SetPoolLogic(ctx, &gpb.PoolLogicReq{Id: uint64(this.CsId), Logic: int64(model.EBaseL_Junk)})
		if err != nil {
			return htp.RespModelErr("", err)
		}
	}

	// 移除工作池
	_, err := model.Work.DelWorkPool(ctx, &gpc.BaseReq{Id: uint64(this.CsId)})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if this.Id != 0 {
		_, err = model.PoolOutNode.EditPoolOutNode(ctx, &gpb.PoolOutNode{
			Id:     this.Id,
			OperId: user.UId,
		})
	}

	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", nil)
}
